#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 作者:微博：天狼50学员_杨执行
# 项目地址：https://gitee.com/sirius-50-students-yang/xiadan
# 基于开源项目：天勤 天勤项目地址：https://gitee.com/tianqin_quantification_tqsdk/tqsdk-python
# license Apache-2.0

from tkinter import *
from tkinter import ttk
import time
import threading
# 时间
import datetime
import http.client
import os
# ini配置文件操作
from configobj import ConfigObj
# 天勤
from tqsdk import TqApi, TqKq, TqAuth, TqAccount, TargetPosTask

######全局变量
# 期货公司用户名密码
company_name = ""
username_company = ""
password_company = ""
ctp_zhuxi = ""
ctp_front_broker = ""
ctp_front_url = ""
# 天勤用户名密码
username_tq = ""
password_tq = ""
# 合约净持仓
positon_sum = 0
# 交易合约
future_index = "IF"
# 保证金比率
ratio_margin = 0.13
# 交易手数
hands = 1
# 交易线程运行状态
trade_state = 0
# 账户
account_float_profit = 0
account_close_profit = 0
account_available = 0
account_balance = 0
account_static_balance = 0
# 登录状态
login_state = 0
#行情
price_quote=""
#主力合约
quote_main_string=""


class MY_GUI():
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name

    # 界面初始化
    def set_init_window(self):
        global positon_sum
        self.style_set = ttk.Style()
        self.style_set.configure("red.TLabel", foreground='red')
        self.style_set.configure("black.TLabel", foreground='black')
        self.style_set.configure("green.TLabel", foreground='green')
        self.style_set.configure("red.TButton", foreground='red')
        self.style_set.configure("black.TButton", foreground='black')
        self.style_set.configure("green.TButton", foreground='green')
        # 开始设置登录界面
        self.init_window_name.title("股指净持仓下单_免费开源")  # 窗口名
        self.init_window_name.geometry('160x600')  # 匹配行情软件 右侧宽度
        # self.init_window_name.resizable(0, 0)  # 停用窗口宽度调整
        self.init_window_name.attributes("-toolwindow", True,"-topmost", True)  # 去掉窗口最大化最小化按钮，只保留关闭; 窗口中处于最顶层
        ###交易账户登录
        self.company_login = ttk.LabelFrame(self.init_window_name, text="交易账号", relief="groove")
        self.company_login.grid(column=0, row=1, sticky='W')
        # 选择期货公司
        self.company_trade_label = ttk.Label(self.company_login, text="期货公司:")
        self.company_trade_label.grid(column=0, row=1, sticky='W')
        self.company_chose = ttk.Combobox(self.company_login)
        self.company_chose['values'] = ("天勤模拟", "A安粮期货", "B倍特期货", "B宝城期货", "C长江期货", "C长城期货", "C创元期货", "D东方汇金", "D大地期货", "D大越期货", "D大有期货", "F福能期货", "G国海良时", "G冠通期货", "G广金期货", "G国元期货", "G国金期货", "G国贸期货", "G国信期货", "G国投安信", "G格林大华", "G国盛期货", "G国泰君安", "H华龙期货", "H红塔期货", "H华鑫期货", "H海航期货", "H恒泰期货", "H宏源期货", "H华安期货", "H华金期货", "H海证期货", "H和合期货", "H和融期货", "H海通期货", "H华闻期货", "H徽商期货", "H混沌天成", "J金石期货", "J建信期货", "J金信期货", "J锦泰期货", "J江海汇鑫", "J江苏东华", "L鲁证期货", "M民生期货", "M迈科期货", "N宁证期货", "N南华期货", "R瑞奇期货", "R瑞达期货", "S山西三立", "S神华期货", "S盛达期货", "S山金期货", "S上海东亚", "S上海东方", "S上海中期", "T通惠期货", "T铜冠金源", "W五矿经易", "X鑫鼎盛期货", "X先锋期货", "X西南期货", "X先融期货", "X新纪元期货", "X西部期货", "X兴证期货", "X新世纪期货", "Y英大期货", "Y一德期货", "Z招金期货", "Z中财期货", "Z中钢期货", "Z中天期货", "Z中原期货", "Z中航期货", "Z中辉期货", "Z中银期货", "Z招商期货", "Z中州期货", "Z中融汇信", "Z浙商期货", "Z中投天琪")
        self.company_chose.grid(column=0, row=2, sticky='W')
        self.company_chose.bind("<<ComboboxSelected>>", self.company_funciton)
        # 期货公司用户名
        self.username_company_label = ttk.Label(self.company_login, text="用户名:")
        self.username_company_label.grid(column=0, row=3, sticky='W')
        self.username_company_entry = ttk.Entry(self.company_login)
        self.username_company_entry.grid(column=0, row=4, sticky='W')
        # 期货公司密码
        self.password_company_label = ttk.Label(self.company_login, text="密码:")
        self.password_company_label.grid(column=0, row=5, sticky='W')
        self.password_company_entry = ttk.Entry(self.company_login,show="*")
        self.password_company_entry.grid(column=0, row=6, sticky='W')
        # 是否为主席
        self.ctp_chose_label = ttk.Label(self.company_login, text="是否为CTP主席:")
        self.ctp_chose_label.grid(column=0, row=7, sticky='W')
        self.ctp_chose = ttk.Combobox(self.company_login)
        self.ctp_chose['values'] = ("CTP主席", "非CTP主席")
        self.ctp_chose.grid(column=0, row=8, sticky='W')
        self.ctp_chose.bind("<<ComboboxSelected>>", self.ctp_funciton)
        # 期货公司bookid
        self.ctp_front_broker_label = ttk.Label(self.company_login, text="期货公司 bookid:")
        self.ctp_front_broker_label.grid(column=0, row=9, sticky='W')
        self.ctp_front_broker_entry = ttk.Entry(self.company_login)
        self.ctp_front_broker_entry.grid(column=0, row=10, sticky='W')
        # 期货公司
        self.ctp_front_url_label = ttk.Label(self.company_login, text="期货公司 ctp_front_url:")
        self.ctp_front_url_label.grid(column=0, row=11, sticky='W')
        self.ctp_front_url_entry = ttk.Entry(self.company_login)
        self.ctp_front_url_entry.grid(column=0, row=12, sticky='W')
        ###行情登录
        self.quotations_login = ttk.LabelFrame(self.init_window_name, text="行情账号", relief="groove")
        self.quotations_login.grid(column=0, row=2, sticky='W')
        self.username_tq_label = ttk.Label(self.quotations_login, text="天勤用户名:")
        self.username_tq_label.grid(column=0, row=1, sticky='W')
        self.username_tq_entry = ttk.Entry(self.quotations_login)
        self.username_tq_entry.grid(column=0, row=2, sticky='W')

        self.password_tq_label = ttk.Label(self.quotations_login, text="天勤密码:")
        self.password_tq_label.grid(column=0, row=3, sticky='W')
        self.password_tq_entry = ttk.Entry(self.quotations_login,show="*")
        self.password_tq_entry.grid(column=0, row=4, sticky='W')
        ###选择交易合约 , text=ratio_margin , text=future_index
        self.future_index_chose_lf = ttk.LabelFrame(self.init_window_name, text="交易合约", relief="groove")
        self.future_index_chose_lf.grid(column=0, row=3, sticky='W')
        self.future_index_chose_cb = ttk.Combobox(self.future_index_chose_lf)
        self.future_index_chose_cb['values'] = ("IF", "IC", "IH")
        self.future_index_chose_cb.grid(column=0, row=1, sticky='W')

        self.ratio_margin_label = ttk.Label(self.future_index_chose_lf, text="保证金比率:")
        self.ratio_margin_label.grid(column=0, row=2, sticky='W')
        self.ratio_margin_chose = ttk.Combobox(self.future_index_chose_lf)
        self.ratio_margin_chose['values'] = (0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30)
        self.ratio_margin_chose.grid(column=0, row=3, sticky='W')

        # 确定
        self.confirm_button = ttk.Button(self.init_window_name, text="启动", command=self.trade_start_ui)
        self.confirm_button.grid(column=0, row=4)

        ###交易界面
        self.order_lframe = ttk.LabelFrame(self.init_window_name, text="下单", relief="groove")
        self.order_lframe.grid(column=0, row=5)
        self.position_sum_label = ttk.Label(self.order_lframe, text="净持仓:")
        self.position_sum_label.grid(column=0, row=1, sticky='W')
        self.position_sum_value_label = ttk.Label(self.order_lframe, text=str(positon_sum), style="black.TLabel")
        self.position_sum_value_label.grid(column=0, row=2, sticky='W')

        self.order_long = ttk.Button(self.order_lframe, text="多", style="red.TButton", command=long_trade_order)
        self.order_long.grid(column=0, row=3, sticky='W')
        self.order_short = ttk.Button(self.order_lframe, text="空", style="green.TButton", command=short_trade_order)
        self.order_short.grid(column=0, row=3, sticky='E')
        self.order_cover = ttk.Button(self.order_lframe, text="平仓", style="black.TButton", command=cover_trade_order)
        self.order_cover.grid(column=0, row=4, columnspan=2)

        self.order_amount_label = ttk.Label(self.order_lframe, text="手数:")
        self.order_amount_label.grid(column=0, row=5, sticky='W')
        self.order_amount_chose = ttk.Combobox(self.order_lframe)
        self.order_amount_chose['values'] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30)
        self.order_amount_chose.grid(column=0, row=6, sticky='E')
        #主力合约 时间
        self.quote_tiem_label = ttk.Label(self.order_lframe, text="主力合约: " + " 价格:")
        self.quote_tiem_label.grid(column=0, row=7, sticky='W')
        ###账户信息
        self.acount_lframe = ttk.LabelFrame(self.init_window_name, text="账户", relief="groove")
        self.acount_lframe.grid(column=0, row=6, sticky='W')

        self.float_profit_label = ttk.Label(self.acount_lframe, text="持仓盈亏:")
        self.float_profit_label.grid(column=0, row=1, sticky='W')

        self.close_profit_label = ttk.Label(self.acount_lframe, text="平仓盈亏:")
        self.close_profit_label.grid(column=0, row=3, sticky='W')

        self.available_label = ttk.Label(self.acount_lframe, text="可用资金:")
        self.available_label.grid(column=0, row=5, sticky='W')

        self.balance_label = ttk.Label(self.acount_lframe, text="动态权益:")
        self.balance_label.grid(column=0, row=7, sticky='W')

        self.static_balance_label = ttk.Label(self.acount_lframe, text="静态权益:")
        self.static_balance_label.grid(column=0, row=9, sticky='W')

        # 停止交易
        self.stop_trade_button = ttk.Button(self.init_window_name, text="停止交易", command=self.trade_stop_ui)
        self.stop_trade_button.grid(column=0, row=7)

        # 异常提示
        self.fail_label = ttk.Label(self.init_window_name, text="", style="red.TLabel")
        self.fail_label.grid(column=0, row=8, sticky='W')
        # 提醒
        self.warning1_label = ttk.Label(self.init_window_name, text="重要提醒：", style="red.TLabel")
        self.warning1_label.grid(column=0, row=9, sticky='W')
        self.warning3_label = ttk.Label(self.init_window_name, text="交易时不能用其它软件下单\n该软件控制所选合约所有持仓", style="red.TLabel")
        self.warning3_label.grid(column=0, row=10, sticky='W')
        self.warning2_label = ttk.Label(self.init_window_name, text="可以开着其它软件查看持仓", style="red.TLabel")
        self.warning2_label.grid(column=0, row=11, sticky='W')
        # 同步本地电脑时间
        self.sync_local_time = ttk.Button(self.init_window_name, text="工具:同步电脑时间(百度时间)", command=get_webservertime)
        self.sync_local_time.grid(column=0, row=13, sticky='W')


        # 隐藏非CTP登录
        self.ctp_front_broker_label.grid_forget()
        self.ctp_front_broker_entry.grid_forget()
        self.ctp_front_url_label.grid_forget()
        self.ctp_front_url_entry.grid_forget()
        # 隐藏交易
        self.order_lframe.grid_forget()
        self.acount_lframe.grid_forget()
        self.stop_trade_button.grid_forget()

        self.fail_label.grid_forget()

    # 交易开始
    def trade_start_ui(self):
        global company_name
        global username_company
        global password_company
        global ctp_zhuxi
        global ctp_front_broker
        global ctp_front_url
        global username_tq
        global password_tq
        global login_state

        global positon_sum

        global future_index
        global ratio_margin
        global hands
        global account_float_profit
        global account_close_profit
        global account_available
        global account_balance
        global account_static_balance
        # 行情
        global price_quote
        # 主力合约
        global quote_main_string

        login_state = 0
        ##读取用户设置参数
        company_name = self.company_chose.get()
        username_company = self.username_company_entry.get()
        password_company = self.password_company_entry.get()

        ctp_zhuxi = self.ctp_chose.get()
        ctp_front_broker = self.ctp_front_broker_entry.get()
        ctp_front_url = self.ctp_front_url_entry.get()

        username_tq = self.username_tq_entry.get()
        password_tq = self.password_tq_entry.get()

        future_index = self.future_index_chose_cb.get()
        ratio_margin = float(self.ratio_margin_chose.get())
        hands = int(self.order_amount_chose.get())
        #启动交易
        trade_start()
        # 提醒
        self.warning1_label.grid_forget()
        self.warning2_label.grid_forget()
        self.warning3_label.grid_forget()
        # 同步本地电脑时间
        self.sync_local_time.grid_forget()
        #交易登录确认 45s登录不成功 登录失败
        for i in range(45):
            time.sleep(1)
            if login_state == 1:
                break
        #确认登录 ui设置为交易界面
        if login_state == 1:
            self.fail_label.grid_forget()
            self.set_trade_window()
            t = threading.Thread(target=self.ui_update)
            t.setDaemon(True)
            t.start()
        #登录失败
        if login_state == 0:
            self.fail_label.grid(column=0, row=8, sticky='W')
            self.fail_label['text'] = "登录异常"

    # 交易停止
    def trade_stop_ui(self):
        global login_state
        #停止交易
        trade_stop()
        #等待15s
        for i_delay in range(15):
            time.sleep(1)
            if login_state==0:
                break
        #用户界面跳转至登录
        self.set_login_window()
        #写入用户设置参数
        self.write_info()

    # 更新ui
    def ui_update(self):
        global positon_sum
        global hands
        global account_float_profit
        global account_close_profit
        global account_available
        global account_balance
        global account_static_balance
        # 行情
        global price_quote
        # 主力合约
        global quote_main_string

        while login_state == 1 & trade_state == 1:
            hands = int(self.order_amount_chose.get())
            if positon_sum > 0:
                self.position_sum_value_label['style'] = "red.TLabel"
            elif positon_sum < 0:
                self.position_sum_value_label['style'] = "green.TLabel"
            else:
                self.position_sum_value_label['style'] = "black.TLabel"

            self.position_sum_value_label['text'] = positon_sum
            self.float_profit_label['text'] = "持仓盈亏:" + str(round(account_float_profit, 0))
            self.close_profit_label['text'] = "平仓盈亏:" + str(round(account_close_profit, 0))
            self.available_label['text'] = "可用资金:" + str(round(account_available, 0))
            self.balance_label['text'] = "动态权益:" + str(round(account_balance, 0))
            self.static_balance_label['text'] = "静态权益:" + str(round(account_balance, 0))
            self.quote_tiem_label['text'] = "主力合约" +quote_main_string+ " 价格"+price_quote
            time.sleep(0.1)

    # CTP下拉列表选择
    def ctp_funciton(self, arg):
        # CTP登录
        if self.ctp_chose.get() == "非CTP主席":
            self.ctp_front_broker_label.grid(column=0, row=9, sticky='W')
            self.ctp_front_broker_entry.grid(column=0, row=10, sticky='W')
            self.ctp_front_url_label.grid(column=0, row=11, sticky='W')
            self.ctp_front_url_entry.grid(column=0, row=12, sticky='W')
        else:
            self.ctp_front_broker_label.grid_forget()
            self.ctp_front_broker_entry.grid_forget()
            self.ctp_front_url_label.grid_forget()
            self.ctp_front_url_entry.grid_forget()

    # 期货公司下拉列表选择
    def company_funciton(self, arg):
        if self.company_chose.get() == "天勤模拟":
            self.quotations_login.grid_forget()
            self.ctp_chose_label.grid_forget()
            self.ctp_chose.grid_forget()

            self.ctp_front_broker_label.grid_forget()
            self.ctp_front_broker_entry.grid_forget()
            self.ctp_front_url_label.grid_forget()
            self.ctp_front_url_entry.grid_forget()
        else:
            self.quotations_login.grid(column=0, row=2, sticky='W')
            self.ctp_chose_label.grid(column=0, row=7, sticky='W')
            self.ctp_chose.grid(column=0, row=8, sticky='W')
            # CTP登录
            self.ctp_funciton(arg=())

    # 登录界面
    def set_login_window(self):

        # 登录界面
        self.company_login.grid(column=0, row=1, sticky='W')
        self.quotations_login.grid(column=0, row=2, sticky='W')
        self.future_index_chose_lf.grid(column=0, row=3, sticky='W')
        self.confirm_button.grid(column=0, row=4)
        # 期货公司下拉列表选择
        self.company_funciton(arg=())
        # 提醒
        self.warning1_label.grid(column=0, row=9, sticky='W')
        self.warning2_label.grid(column=0, row=11, sticky='W')
        self.warning3_label.grid(column=0, row=10, sticky='W')
        # 同步本地电脑时间
        self.sync_local_time.grid(column=0, row=12, sticky='W')
        # 交易
        self.order_lframe.grid_forget()
        self.acount_lframe.grid_forget()
        self.stop_trade_button.grid_forget()

        self.init_window_name.geometry('160x600')

    # 交易界面
    def set_trade_window(self):
        # CTP登录
        self.ctp_front_broker_label.grid_forget()
        self.ctp_front_broker_entry.grid_forget()
        self.ctp_front_url_label.grid_forget()
        self.ctp_front_url_entry.grid_forget()
        # 登录界面
        self.company_login.grid_forget()
        self.quotations_login.grid_forget()
        self.future_index_chose_lf.grid_forget()
        self.confirm_button.grid_forget()
        # 提醒
        self.warning1_label.grid_forget()
        self.warning2_label.grid_forget()
        self.warning3_label.grid_forget()
        # 同步本地电脑时间
        self.sync_local_time.grid_forget()
        # 交易
        self.order_lframe.grid(column=0, row=5)
        self.acount_lframe.grid(column=0, row=6, sticky='W')
        self.stop_trade_button.grid(column=0, row=7)

        self.init_window_name.geometry('160x350')

    # 读取配置文件设置信息
    def read_info(self):
        global company_name
        global username_company
        global password_company
        global ctp_zhuxi
        global ctp_front_broker
        global ctp_front_url
        global username_tq
        global password_tq

        global positon_sum

        global future_index
        global ratio_margin
        global hands
        global account_float_profit
        global account_close_profit
        global account_available
        global account_balance
        global account_static_balance
        info_file = ConfigObj("userinfo.ini", encoding='UTF8')
        company_name = info_file["info"]["company_name"]
        username_company = info_file["info"]["username_company"]
        password_company = info_file["info"]["password_company"]
        ctp_zhuxi = info_file["info"]["ctp_zhuxi"]
        ctp_front_broker = info_file["info"]["ctp_front_broker"]
        ctp_front_url = info_file["info"]["ctp_front_url"]

        username_tq = info_file["info"]["username_tq"]
        password_tq = info_file["info"]["password_tq"]

        future_index = info_file["info"]["future_index"]
        hands = info_file["info"]["hands"]
        ratio_margin = info_file["info"]["ratio_margin"]
        print("读取配置信息")
        # 读取配置文件设置信息

    def load_info(self):
        global company_name
        global username_company
        global password_company
        global ctp_zhuxi
        global ctp_front_broker
        global ctp_front_url
        global username_tq
        global password_tq

        global positon_sum

        global future_index
        global ratio_margin
        global hands
        global account_float_profit
        global account_close_profit
        global account_available
        global account_balance
        global account_static_balance

        self.company_chose.select_clear()
        self.username_company_entry.select_clear()
        self.password_company_entry.select_clear()
        self.ctp_chose.select_clear()
        self.ctp_front_broker_entry.select_clear()
        self.ctp_front_url_entry.select_clear()

        self.company_chose.insert(0, str(company_name))
        self.username_company_entry.insert(0, str(username_company))
        self.password_company_entry.insert(0, str(password_company))
        self.ctp_chose.insert(0, str(ctp_zhuxi))
        self.ctp_front_broker_entry.insert(0, str(ctp_front_broker))
        self.ctp_front_url_entry.insert(0, str(ctp_front_url))

        self.username_tq_entry.select_clear()
        self.password_tq_entry.select_clear()

        self.username_tq_entry.insert(0, str(username_tq))
        self.password_tq_entry.insert(0, str(password_tq))

        self.future_index_chose_cb.select_clear()
        self.ratio_margin_chose.select_clear()
        self.order_amount_chose.select_clear()

        self.future_index_chose_cb.insert(0, str(future_index))
        self.ratio_margin_chose.insert(0, str(ratio_margin))
        self.order_amount_chose.insert(0, str(hands))

        print("信息写入输入框")

    # 信息写入配置文件
    def write_info(self):
        global company_name
        global username_company
        global password_company
        global ctp_zhuxi
        global ctp_front_broker
        global ctp_front_url
        global username_tq
        global password_tq

        global positon_sum

        global future_index
        global ratio_margin
        global hands
        global account_float_profit
        global account_close_profit
        global account_available
        global account_balance
        global account_static_balance

        company_name = self.company_chose.get()
        username_company = self.username_company_entry.get()
        password_company = self.password_company_entry.get()

        ctp_zhuxi = self.ctp_chose.get()
        ctp_front_broker = self.ctp_front_broker_entry.get()
        ctp_front_url = self.ctp_front_url_entry.get()

        username_tq = self.username_tq_entry.get()
        password_tq = self.password_tq_entry.get()

        future_index = self.future_index_chose_cb.get()
        ratio_margin = self.ratio_margin_chose.get()

        info_file = ConfigObj("userinfo.ini", encoding='UTF8')
        info_file["info"]["company_name"] = company_name
        info_file["info"]["username_company"] = username_company
        info_file["info"]["password_company"] = password_company
        info_file["info"]["ctp_zhuxi"] = ctp_zhuxi
        info_file["info"]["ctp_front_broker"] = ctp_front_broker
        info_file["info"]["ctp_front_url"] = ctp_front_url

        info_file["info"]["username_tq"] = username_tq
        info_file["info"]["password_tq"] = password_tq

        info_file["info"]["future_index"] = future_index

        info_file["info"]["hands"] = hands

        info_file["info"]["ratio_margin"] = ratio_margin
        info_file.write()
        print("写入配置信息")


# 开多
def long_trade_order():
    global positon_sum
    global hands
    positon_sum = positon_sum + int(hands)


# 开空
def short_trade_order():
    global positon_sum
    global hands
    positon_sum = positon_sum - int(hands)


# 平仓
def cover_trade_order():
    global positon_sum
    global hands
    if positon_sum == 0:
        positon_sum = 0
    elif positon_sum > 0:
        if positon_sum > int(hands):
            positon_sum = positon_sum - int(hands)
        else:
            positon_sum = 0
    else:
        if abs(positon_sum) > int(hands):
            positon_sum = positon_sum + int(hands)
        else:
            positon_sum = 0


# 停止交易
def trade_stop():
    global trade_state
    trade_state = 0


# 启动交易进程
def trade_start():
    global trade_state
    trade_state = 1
    t = threading.Thread(target=trade)
    t.setDaemon(True)
    t.start()


# 交易进程
def trade():
    global company_name
    global username_company
    global password_company
    global ctp_zhuxi
    global ctp_front_broker
    global ctp_front_url
    global username_tq
    global password_tq
    global login_state
    global positon_sum

    global future_index
    global ratio_margin
    global hands
    global account_float_profit
    global account_close_profit
    global account_available
    global account_balance
    global account_static_balance
    # 行情
    global price_quote
    # 主力合约日期
    global quote_main_string
    quote_main_string = ""
    dt_quote=datetime.datetime
    positon_sum = 0
    # 点价格
    price_point = 300
    if future_index == "IC":
        price_point = 200
    print(company_name)
    print(username_company)
    print(password_company)
    print(ctp_zhuxi)
    print(ctp_front_broker)
    print(ctp_front_url)
    print(username_tq)
    print(password_tq)
    print(future_index)

    # 开始交易
    if trade_state == 1:
        # 登录
        if company_name == "天勤模拟":
            api = TqApi(TqKq(), auth=TqAuth(username_company, password_company))
            login_state = 1
        elif ctp_zhuxi == "非CTP主席":
            api = TqApi(TqAccount(company_name, username_company, password_company, front_broker=ctp_front_broker, front_url=ctp_front_url), auth=TqAuth(username_tq, password_tq))
            login_state = 1
        else:
            api = TqApi(TqAccount(company_name, username_company, password_company), auth=TqAuth(username_tq, password_tq))
            login_state = 1
    # 是否交易日-交易日期判断
    trade_day = api.get_trading_calendar(start_dt=datetime.date.today(), end_dt=datetime.date.today())

    if trade_day.trading[0]:
        # 查询持仓
        account = api.get_account()
        delivery = 0
        # 账户
        account_float_profit = account.float_profit
        account_close_profit = account.close_profit
        account_available = account.available
        account_balance = account.balance
        account_static_balance = account.static_balance

        # 获得主力合约代码--上市合约中是否存在月份小于主力合约月份
        list_product_main_if = api.query_cont_quotes(exchange_id="CFFEX", product_id="IF")
        list_product_all_if = api.query_quotes(ins_class="FUTURE", exchange_id="CFFEX", product_id="IF", expired=False)
        main_month = int(list_product_main_if[0][-4:])
        delivery_product_day = 0
        delivery_month = int(list_product_main_if[0][-4:])
        for product_each in list_product_all_if:
            if int(product_each[-4:]) < main_month:
                delivery_product_day = 1
                delivery_month = int(product_each[-4:])
        # 查询非主力合约持仓
        if delivery_product_day == 1:
            # 交割合约
            product_delivery = "CFFEX." + future_index + str(delivery_month)
            # 持仓
            position_delivery = api.get_position(product_delivery)
            if abs(position_delivery.pos_long_his) + abs(position_delivery.pos_short_his) > 0:
                delivery = 1
                # 行情
                quote_delivery = api.get_quote(product_delivery)
                # 交割合约下单
                target_pos_delivery = TargetPosTask(api, product_delivery, price='ACTIVE', offset_priority="昨开")
                # 实际下单手数
                positon_order_delivery = 0
                # 初始净持仓
                positon_sum = position_delivery.pos_long_his - position_delivery.pos_short_his

        # 主力合约:持仓 行情 目标持仓
        product_main = "CFFEX." + future_index + str(main_month)
        quote_main_string=future_index + str(main_month)
        # 持仓
        position_main = api.get_position(product_main)
        # 行情
        quote_main = api.get_quote(product_main)
        # 下单
        target_pos_main = TargetPosTask(api, product_main, price='ACTIVE', offset_priority="昨开")

        # 实际下单手数
        positon_order_main = 0
        # 初始净持仓（累加上交割合约的持仓手数）
        positon_sum = positon_sum + position_main.pos_long_his - position_main.pos_short_his + position_main.pos_long_today - position_main.pos_short_today
        print("主力合约名称")
        print(product_main)
        # 交易循环 维护 净持仓
        while trade_state == 1:
            api.wait_update()
            if api.is_changing(quote_main):
                # 账户
                account_float_profit = account.float_profit
                account_close_profit = account.close_profit
                account_available = account.available
                account_balance = account.balance
                account_static_balance = account.static_balance
                # 时间
                price_quote = str(quote_main.last_price)
                # 无交割合约解锁
                if delivery == 0:
                    if positon_sum == 0:
                        positon_order_main = 0
                        target_pos_main.set_target_volume(positon_order_main)
                    if positon_sum > 0:
                        # 可用资金>保证金*保证金手数
                        if account.available > quote_main.last_price * price_point * ratio_margin * (positon_sum - position_main.pos_long_his):
                            positon_order_main = positon_sum
                            target_pos_main.set_target_volume(positon_order_main)
                        # 可用资金<保证金*手数--净持仓不变
                        else:
                            positon_sum = position_main.pos_long_his - position_main.pos_short_his + position_main.pos_long_today - position_main.pos_short_today
                    if positon_sum < 0:
                        if account.available > quote_main.last_price * price_point * ratio_margin * (abs(positon_sum) - position_main.pos_short_his):
                            positon_order_main = positon_sum
                            target_pos_main.set_target_volume(positon_order_main)
                        # 可用资金<保证金*手数--净持仓不变
                        else:
                            positon_sum = position_main.pos_long_his - position_main.pos_short_his + position_main.pos_long_today - position_main.pos_short_today
                # 有交割合约解锁
                if delivery == 1:
                    if positon_sum == 0:
                        positon_order_main = 0
                        positon_order_delivery = 0
                        target_pos_main.set_target_volume(positon_order_main)
                        target_pos_delivery.set_target_volume(positon_order_delivery)
                    if positon_sum > 0:
                        # 可用资金>保证金*保证金手数
                        if account.available > quote_main.last_price * price_point * ratio_margin * (positon_sum - position_main.pos_long_his - position_delivery.pos_long_his):
                            if positon_sum <= position_delivery.pos_long_his:
                                positon_order_main = 0
                                positon_order_delivery = positon_sum
                                target_pos_main.set_target_volume(positon_order_main)
                                target_pos_delivery.set_target_volume(positon_order_delivery)
                            if positon_sum > position_delivery.pos_long_his:
                                positon_order_main = positon_sum - position_delivery.pos_long_his
                                positon_order_delivery = position_delivery.pos_long_his
                                target_pos_main.set_target_volume(positon_order_main)
                                target_pos_delivery.set_target_volume(positon_order_delivery)
                        # 可用资金<保证金*手数--净持仓不变
                        else:
                            positon_sum = position_main.pos_long_his - position_main.pos_short_his + position_main.pos_long_today - position_main.pos_short_today + position_delivery.pos_long_his - position_delivery.pos_short_his
                    if positon_sum < 0:
                        # 可用资金>保证金*保证金手数
                        if account.available > quote_main.last_price * price_point * ratio_margin * (abs(positon_sum) - position_main.pos_short_his - position_delivery.pos_short_his):
                            if abs(positon_sum) <= position_delivery.pos_short_his:
                                positon_order_main = 0
                                positon_order_delivery = positon_sum
                                target_pos_main.set_target_volume(positon_order_main)
                                target_pos_delivery.set_target_volume(positon_order_delivery)
                            if abs(positon_sum) > position_delivery.pos_long_his:
                                positon_order_main = -(abs(positon_sum) - position_delivery.pos_long_his)
                                positon_order_delivery = -position_delivery.pos_long_his
                                target_pos_main.set_target_volume(positon_order_main)
                                target_pos_delivery.set_target_volume(positon_order_delivery)
                        # 可用资金<保证金*手数--净持仓不变
                        else:
                            positon_sum = position_main.pos_long_his - position_main.pos_short_his + position_main.pos_long_today - position_main.pos_short_today + position_delivery.pos_long_his - position_delivery.pos_short_his

        # 天勤api close
        if trade_state == 0:
            api.close()
            login_state = 0
            print("停止交易")
            print("login_state")
            print(login_state)
# 同步本地时间 函数
def get_webservertime():
    host="www.baidu.com"
    conn = http.client.HTTPConnection(host)
    conn.request("GET", "/")
    r = conn.getresponse()
    # r.getheaders() #获取所有的http头
    ts = r.getheader('date')  # 获取http头date部分
    # 将GMT时间转换成北京时间
    ltime = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
    #print("ltime")
    #print(ltime)
    ttime = time.localtime(time.mktime(ltime) + 8 * 60 * 60)
    #print("ttime")
    #print(ttime)
    dat = "date %u-%02u-%02u" % (ttime.tm_year, ttime.tm_mon, ttime.tm_mday)
    tm = "time %02u:%02u:%02u" % (ttime.tm_hour, ttime.tm_min, ttime.tm_sec)
    #print(dat, tm)
    os.system(dat)
    os.system(tm)

# 加载界面
def gui_start():
    init_window = Tk()
    gui = MY_GUI(init_window)
    gui.read_info()
    gui.set_init_window()
    gui.load_info()
    gui.set_login_window()
    init_window.mainloop()


###启动
gui_start()
